package com.kool.kadmin.mqtt.service;

import com.kool.kadmin.common.bean.PageListResult;
import com.kool.kadmin.common.constant.ErrorCode;
import com.kool.kadmin.common.exception.AppException;
import com.kool.kadmin.common.util.PaginatorUtil;
import com.kool.kadmin.common.util.ResultUtil;
import com.kool.kadmin.mqtt.bean.MqttClientDo;
import com.kool.kadmin.mqtt.dao.MqttClientDao;
import com.kool.kadmin.mqtt.request.AddClientReq;
import com.kool.kadmin.mqtt.request.DeleteClientReq;
import com.kool.kadmin.mqtt.request.GetClientPageReq;
import com.kool.kadmin.mqtt.request.UpdateClientReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author luyu
 * @date 2021-04-19 16:58
 */
@Service
@Slf4j
public class MqttClientService {
    @Resource
    private MqttClientDao clientDao;

    /**
     * 分页查询客户端设备信息
     *
     * @param request
     * @return
     */
    public PageListResult getClientPage(GetClientPageReq request) {
        MqttClientDo condition = new MqttClientDo();
        condition.setClientId(request.getClientId());
        condition.setUserName(request.getUserName());

        int total = clientDao.countTotal(condition);
        int offset = PaginatorUtil.calculateOffset(request.getCurrentPage(), request.getPageSize());
        List<MqttClientDo> list = clientDao.getPage(condition, offset, request.getPageSize());
        return ResultUtil.success(list, request.getCurrentPage(), request.getPageSize(), total);
    }

    /**
     * 新增客户端设备信息
     *
     * @param request
     */
    public void addClient(AddClientReq request) {
        String clientId = request.getClientId();
        //查询客户端是否存在
        MqttClientDo client = clientDao.getByClientId(clientId);
        if (client != null) {
            throw new AppException(ErrorCode.BUSINESS_ERROR, String.format("客户端【%s】已存在", clientId));
        }
        client = new MqttClientDo();
        client.setClientId(request.getClientId())
                .setClientType(request.getClientType())
                .setClientDesc(request.getClientDesc())
                .setUserName(request.getUserName())
                .setRefId(request.getRefId());

        clientDao.insert(client);
    }

    /**
     * 更新客户端设备信息
     *
     * @param request
     */
    public void updateClient(UpdateClientReq request) {
        MqttClientDo client = new MqttClientDo();
        client.setId(request.getId())
                .setClientId(request.getClientId())
                .setClientType(request.getClientType())
                .setClientDesc(request.getClientDesc())
                .setUserName(request.getUserName())
                .setRefId(request.getRefId());

        clientDao.updateById(client);
    }

    /**
     * 删除客户端设备信息
     *
     * @param request
     */
    public void deleteClient(DeleteClientReq request) {
        clientDao.deleteById(request.getId());
    }
}
